<script setup lang="ts">
import { onMounted, computed } from 'vue';
import { eventCenter, navigateTo, showLoading, reLaunch, getCurrentInstance } from '@tarojs/taro';
import { QUERY_APP_FLOW_PATH_RECORD_LIST } from '/@/api/modules/flow-path/flow-path';
import { APPROVE_STATUE, APPROVE_STATUE_COLOR, APPROVE_STATUE_BG_COLOR } from '/@/common/constant';
import { approveState } from './state';
import { isJsonString } from '/@/utils/string-util';
/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as unknown as {
  from?: string;
  title?: string;
  templateCodeList?: string;
  templateCode?: string;
};

onMounted(() => {
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    refreshRecordList();
  });
});

/**
 * @description 跳转到详情页面
 * @param item 点击的item项
 */
function jumpToDetailPage(item: FlowPathDto.RecordDto) {
  navigateTo({
    url: `/pages/my-approve/detail/index?id=${item.id}&from=send`,
  });
}

/**
 * 不同模块对应的templateCode
 * 根据templateCode查询不同的模块审批记录
 *
 */
const FLOW_PATH_CONSTANT = {
  meeting: 'ba9d82b3-3fa8-4a60-a24f-a924fa95d26d',
  spare: 'bfe18bff-9c61-4416-a305-e293ad976fa8',
  park: 'c16184f3-e5be-4d63-b7cc-ded18b2979e4',
  police_security: '1092b265-6fa0-426b-8626-01edb850af48,ca50ddff-3d06-46d6-b6db-671fe33adb7c',
  custom: params.templateCodeList,
  custom_single: params.templateCodeList,
  item_receive_single: params.templateCodeList,
  repair_single: params.templateCode,
  store_room_single: 'a4a3dfda-32eb-4dec-b3be-5a337289afe0',
};
/**
 * 不同模块tab-pane上显示的名字不同
 * 默认申请记录
 */
const FLOW_PATH_TITLE_CONSTANT = {
  meeting: ['会议室', '预约记录'],
  spare: ['发起申请', '申请记录'],
  park: ['我的车辆', '申请记录'],
  police_security: ['发起申请', '申请记录'],
  custom: ['发起审批', '申请记录'],
  custom_single: ['发起申请', '申请记录'],
  item_receive_single: ['发起申请', '申请记录'],
  repair_single: ['发起申请', '申请记录'],
  store_room_single: ['发起申请', '申请记录'],
};

/**
 * 不同模块tab切换的路径
 */
const FLOW_PATH_TAB_PATH_CONSTANT = {
  meeting: '/pages/meeting/list/index',
  spare: '/pages/spare/list/index',
  park: '/pages/park/list/index',
  police_security: `/pages/police-security/list/index&templateCodeList=${params.templateCodeList}`,
  custom: `/pages/custom-approve/list/index?title=${params.title}&templateCodeList=${params.templateCodeList}`,
  custom_single: `/pages/custom-approve-single/edit/index?title=${params.title}&templateCodeList=${params.templateCodeList}`,
  item_receive_single: `/pages/police-security/item-receive-custom/index?title=${params.title}&templateCodeList=${params.templateCodeList}`,
  repair_single: `/pages/police-security/repair/edit-single/index?templateCode=${params.templateCode}`,
  store_room_single: '/pages/police-security/store-room/index',
};

/**
 * 不同模块nav上的title
 */
const FLOW_PATH_NAV_TITLE_CONSTANT = {
  meeting: '会议预约',
  spare: '耗材申请',
  park: '停车服务',
  police_security: '警保业务申请',
  custom: params.title ? decodeURI(params.title) : '申请事项',
  custom_single: params.title ? decodeURI(params.title) : '申请事项',
  item_receive_single: params.title ? decodeURI(params.title) : '申请事项',
  repair_single: '申请事项',
  store_room_single: '库房申领',
};

/**
 * 申请记录
 *@description 审批列表
 * @param page 当前页
 * @param pageSize -每页条数
 */
function queryFlowPathRecordList(page: number = 1, pageSize: number = 15) {
  if (!page && approveState.finished) return;
  approveState.loading = true;
  showLoading();
  QUERY_APP_FLOW_PATH_RECORD_LIST({
    comQuery: { page, pageSize },
    //会议预约审批流程
    templateCodeList: params.from ? FLOW_PATH_CONSTANT[params.from].split(',') : [],
    myHandleStatus: '3',
  })
    .then((res) => {
      approveState.loading = false;
      if (
        approveState.activePage >=
        (res.comQuery?.pageCount ||
          (res.comQuery?.totalCount as number) / (res.comQuery?.pageSize as number) ||
          1)
      ) {
        approveState.finished = true;
      }
      if (!res.flowpathRecordDto || !res.flowpathRecordDto.length) return;
      res.flowpathRecordDto.forEach((item) => approveState.list.push(item));
      approveState.activePage += 1;
    })
    .catch(() => {
      approveState.loading = false;
    });
}

/**
 * @function 加载
 */
function onLoadingRecord() {
  if (approveState.finished) return;
  queryFlowPathRecordList(approveState.activePage);
}

/**
 * 申请记录列表刷新
 */
function refreshRecordList() {
  approveState.activePage = 1;
  approveState.loading = true;
  approveState.finished = false;
  approveState.list = [];
  onLoadingRecord();
}

const displayAttributeValue = computed(() => {
  return (item: FlowPathTemplateApi.AttributeDto) => {
    if (item.attributeTypeName === 'radio' || item.attributeType === 6) {
      //单选项不为空才解析
      if (
        item.attributeOption &&
        item.attributeOption.length > 0 &&
        isJsonString(item.attributeOption)
      ) {
        const objArr: { name: string; value: string }[] = JSON.parse(item.attributeOption);
        const selectedItem = objArr.find((subItem) => subItem.value === item.attributeValue);
        return selectedItem?.name || '';
      }
    } else if (item.attributeTypeName === 'checkbox' || item.attributeType === 7) {
      //单选项不为空才解析
      if (
        item.attributeOption &&
        item.attributeOption.length > 0 &&
        isJsonString(item.attributeOption) &&
        item.attributeValue
      ) {
        const objArr: { name: string; value: string }[] = JSON.parse(item.attributeOption);
        const values = item.attributeValue.split(',');
        const radioValArr = objArr.filter((item) => values.includes(item.value));
        return radioValArr.map((item) => item.name).join(', ');
      }
    } else if (item.attributeTypeName === 'department' || item.attributeType === 11) {
      //单选项不为空才解析
      if (item.attributeValue && isJsonString(item.attributeValue)) {
        const deptObj: { id: string; name: string } = JSON.parse(item.attributeValue);
        return deptObj.name;
      }
    } else {
      return item.attributeValue;
    }
  };
});
</script>

<template>
  <view class="approve-record app-page--1">
    <app-navbar :title="params.from ? FLOW_PATH_NAV_TITLE_CONSTANT[params.from] : '申请事项'" />
    <nut-tabs
      model-value="record"
      @click="
        ({ paneKey }) => {
          if (paneKey === 'list') {
            reLaunch({
              url: params.from
                ? FLOW_PATH_TAB_PATH_CONSTANT[params.from]
                : '/pages/approve/list/index',
            });
          }
        }
      "
    >
      <nut-tab-pane
        :title="params.from ? FLOW_PATH_TITLE_CONSTANT[params.from][0] : '发起审批'"
        pane-key="list"
      />
      <nut-tab-pane
        :title="params.from ? FLOW_PATH_TITLE_CONSTANT[params.from][1] : '申请记录'"
        pane-key="record"
      />
    </nut-tabs>
    <scroll-view
      class="app-page__wrapper"
      :scroll-y="true"
      :lower-threshold="100"
      @scrolltolower="onLoadingRecord()"
    >
      <view class="approve-record__wrapper">
        <view
          class="approve-record__item"
          v-for="item in approveState.list"
          :key="item.id || ''"
          @click="jumpToDetailPage(item)"
        >
          <view class="approve-record__item__header">
            <view class="approve-record__item__header--left">
              <text>{{ item.title || '-' }}</text>
            </view>
            <view
              class="approve-record__item__header--right"
              :style="{
                color: item.status ? APPROVE_STATUE_COLOR[item.status] : '#999',
                backgroundColor: item.status ? APPROVE_STATUE_BG_COLOR[item.status] : '#999',
              }"
            >
              <text>{{ item.status ? APPROVE_STATUE[item.status] : '-' }}</text>
            </view>
          </view>
          <view v-for="attribute in item.attributes" :key="attribute.id">
            <text>{{ attribute.attributeName }}:&nbsp;&nbsp;</text>
            <!--如果属性为单选或者多选 要特殊处理 -->
            <text>{{ displayAttributeValue(attribute) }}</text>
          </view>
        </view>
      </view>
      <view class="app-page__list-tips">
        <text v-if="!approveState.list.length">暂无数据！</text>
        <text v-else-if="approveState.list.length && approveState.loading">加载中...</text>
        <text v-else-if="approveState.list.length && approveState.finished">加载完成!</text>
      </view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
